package servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import domain.Item;
import impl.Petstore;
import shiliImpl.PetstoreImpl;

import shopCart.Cart;
import shopCart.CartItem;

public class CartServlet extends HttpServlet{
	public void doPost(HttpServletRequest request,HttpServletResponse
			response) throws ServletException, IOException{
		doGet(request,response);
	}
	
	public void doGet(HttpServletRequest request,HttpServletResponse
			response) throws ServletException, IOException{
		String action=request.getParameter("action");
		if(action.equals("add")){
			try {
				addItemToCart(request);
			} catch (Exception e) {
			}
		}else if(action.equals("remove")){
			removeItemFromCart(request);
		}else{
			updateCartQuantities(request);
		}
		RequestDispatcher rd=request.getRequestDispatcher("Cart.jsp");
		rd.forward(request,response);
	}
	
	public void addItemToCart (HttpServletRequest request) throws Exception{
		HttpSession session=request.getSession();
		Cart cart=(Cart) session.getAttribute("cart");
		Petstore petstore = (Petstore) session.getAttribute("petstore");
		if(petstore==null){
			petstore = new PetstoreImpl();
			session.setAttribute("petstore", petstore);
		}
		if(cart==null){
			cart=new Cart();
		}
		String itemid=request.getParameter("itemid");
		Item item=petstore.getItem(itemid);
		cart.addItemToCart(item);
		session.setAttribute("cart", cart);
	}
	
	public void removeItemFromCart(HttpServletRequest request){
		HttpSession session=request.getSession();
		Cart cart=(Cart)session.getAttribute("cart");
		String itemid=request.getParameter("itemid");
		cart.removeItemByItemid(itemid);
	}
	
	public void updateCartQuantities(HttpServletRequest request){
		HttpSession session=request.getSession();
		Cart cart=(Cart)session.getAttribute("cart");
		ArrayList<CartItem> cartItems=cart.getCartItemList();
		for(int i=0;i<cartItems.size();i++){
			CartItem cartItem=(CartItem) cartItems.get(i);
			String id=cartItem.getItem().getItemid();
			int qty = 0;
			try{
				qty=Integer.parseInt(request.getParameter(id));
			}catch(Exception e) {
				e.printStackTrace();
				qty = cartItem.getQty();
			}
			cartItem.setQty(qty);
			
		}
	}
}
